/**
 * 申请退款弹窗
 */
import { message, Descriptions, Divider, Form, Spin, Modal } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { getOnceOrderDetail, updateOnceOrderStatus } from '@/services/order/api';
import { EditableProTable } from '@ant-design/pro-table';
import { ModalForm } from '@ant-design/pro-form';
import { isNull, inArray, showMsg } from '@/utils/utils';
import { museText } from '../Detail';

interface MyProps {
  id: string; // 订单id
  onFinish?: Function; // 提交退款申请
  onClose: Function; // 关闭弹窗
}

const Refund: React.FC<MyProps> = (props) => {
  const { id, onFinish, onClose } = props;
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  // 订单详情对象
  const [orderObj, setOrderObj] = useState({ order_goods_list: [] });
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  // 正在编辑的行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  // 表格数据源
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  // 选中的行
  const [selectedRow, setSelectedRow] = useState([]);
  const [modal, contextHolder] = Modal.useModal();
  // 结余
  const [jy, setJy] = useState(0);
  // 退款总金额
  const [total, setTotal] = useState(0);
  // 验光数据-眼科用到
  const [ygData, setYgData] = useState([]);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  type DataSourceType = {
    id: React.Key;
    title?: string;
    decs?: string;
    state?: string;
    created_at?: string;
    children?: DataSourceType[];
  };
  // 格式化配镜数据
  const formatData = (value) => {
    return isNull(value) ? '无' : parseFloat(value) >= 0 ? `+${parseFloat(value).toFixed(2)}` : parseFloat(value).toFixed(2)
  }


  useEffect(() => {
    if (id) {
      getOnceOrderDetail(id).then((res) => {
        setOrderObj(res);
        const data = [{
          c1: '右眼（R）',
          c2: formatData(res.right_degrees),
          c3: formatData(res.right_astig),
          c4: res.right_axial,
          c5: res.right_rectify_bef,
          c6: res.right_rectify_af,
          c7: res.pup_distance_right,
          c8: res.pup_distance,
          c9: res.pup_high_right,
          c11: res.right_defocus,
          c12: res.madd
        }, {
          c1: '左眼（L）',
          c2: formatData(res.left_degrees),
          c3: formatData(res.left_astig),
          c4: res.left_axial,
          c5: res.left_rectify_bef,
          c6: res.left_rectify_af,
          c7: res.pup_distance_left,
          c8: res.pup_distance,
          c9: res.pup_high_left,
          c11: res.left_defocus,
          c12: res.madd
        }];
        // 配镜服务费额外用一行记录标识
        if (!isNull(res.refund_service_price) && parseFloat(res.refund_service_price) > 0) {
          res.refund_order_goods_list.push({ id: '10086', goods_name: '配镜服务费', goods_total_price: res.refund_service_price });
        }
        setYgData(data);
        let price = 0;
        let ratio = parseFloat(res.discount_ratio);
        ratio = ratio === 0 ? 0.01 : ratio;
        res.order_goods_list.forEach(element => {
          price = price + (parseFloat(element.goods_total_price) * ratio);
        });
        // 计算结余
        if (parseFloat(res.discount_ratio) > 0) {
          setJy(parseFloat(parseFloat(res.sett_price) - price));
        }
        form.resetFields();
        actionRef.current && actionRef.current.reload();
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });
    }
  }, [id]);

  // 获得最大退款金额
  const getMaxRefund = (record, index) => {
    // var price = 0;
    // const goodsNum = getGoodsNum(orderObj.order_goods_list);
    // console.log('goodsNum', goodsNum)
    const price = parseFloat(record.discount_price / orderObj.total_price * orderObj.sett_price).toFixed(2);
    // if (parseFloat(orderObj.discount_ratio) === 0) {
    //   if (goodsNum === 1) {
    //     price = orderObj.sett_price;
    //   } else {
    //     price = parseFloat(parseFloat(orderObj.sett_price) / goodsNum).toFixed(2);
    //   }
    //   console.log('price', price)

    //   // price = parseFloat(record.goods_num * 0.01).toFixed(2);
    // } else {
    //   price = parseFloat(parseFloat(record.goods_total_price) * parseFloat(orderObj.discount_ratio)).toFixed(2);
    // }
    // console.log('price', price)
    // if (index === orderObj.order_goods_list.length - 1) {
    //   price = parseFloat(parseFloat(price) + jy).toFixed(2);
    // }

    // console.log('price', price)
    return price;
  }

  // 提交审批
  const onSubmit = () => {
    // console.log('submit', dataSource, editForm.getFieldsError(), total);
    // console.log('selectedRowKeys', selectedRow, editForm.getFieldsValue());
    const refundList = editForm.getFieldsValue(); // 退款列表
    const editErrorList = editForm.getFieldsError(); // 未通过表单验证的列表
    const refund_price = parseFloat(total);
    let result = false;
    for (let i = 0; i < editErrorList.length; i++) {
      const element = editErrorList[i];
      if (!isNull(element.errors)) {
        result = true;
        break;
      }
    }
    // 有表单验证不通过的，则return
    if (result) {
      return;
    }
    if (isNull(selectedRow)) {
      message.error('请选择要退款的商品！');
      return;
    }

    const list = [];
    selectedRow.forEach(element => {
      console.log('element', element)
      if (element.goods_id !== '10086', refundList) {
        element.goods_num = refundList[element.record_id].goods_num;
        element.goods_total_price = refundList[element.record_id].refundPrice;
        list.push(element);
      }
    });
    console.log('selectedRow-list', list, refundList);
    const params = {
      order_id: id,
      refund_order_goods_list: list,
      refund_price,
      refund_service_price: isNull(refundList['10086']) ? 0 : refundList['10086'].refundPrice, // 配镜服务费
      order_status: 'A',
    }
    console.log('params1111', params);
    // return;
    if (!result) {
      setLoading(true);
      return new Promise((resolve) => {
        updateOnceOrderStatus(params).then((res) => {
          setLoading(false);
          if (res !== 'error' || isNull((res || {}).errmsg)) {
            modal.info({ title: '提示', content: '退款请求已提交，等待审批', onOk() { onFinish(); } });
          }
          resolve(true);
        }).catch(res => {
          setLoading(false);
          message.error(res.data.errmsg);
          resolve(true);
        })
      });
    } else {
      message.error('请修改')
    }
  };
  // 计算总金额
  const getTotalPrice = () => {
    setTimeout(() => {
      console.log('getTotalPrice-selectedRowKeys', selectedRow, editForm.getFieldsValue());
      let price = 0;
      let maxprice = 0; // 没用上？先留着吧
      // eslint-disable-next-line no-restricted-syntax
      for (const key in editForm.getFieldsValue()) {
        const element = editForm.getFieldsValue()[key];
        // console.log('element', element)
        price = parseFloat(price + parseFloat(element.refundPrice || 0));
      }
      console.log('selectedRow', selectedRow);
      selectedRow.forEach(element => {
        maxprice = parseFloat(maxprice + getMaxRefund(element));
      });
      console.log('price11111', maxprice);
      setTotal(price.toFixed(2));
      if (parseFloat(price) > 0) {
        orderObj.maxrefund = parseFloat(price);
        setOrderObj(orderObj);
      }
    }, 100);
  }
  // 选择行
  const selectRow = (selected: any, selectedRows: any) => {
    // setSelectedDataList(selectedRows);
    console.log('selectedRows', selected, selectedRows)

    const keys = (selectedRows || []).map((item) => item.record_id)
    setEditableRowKeys(keys);
    (orderObj.order_goods_list || []).map((item, key) => {
      if (isNull(selected) || !inArray(selected, item.record_id)) {
        dataSource[key] = { ...item, id: item.record_id };
      }
    });
    setDataSource(dataSource);
    setSelectedRow(selectedRows);
    getTotalPrice();
    actionRef.current && actionRef.current.reload();
    form.setFieldsValue({ refundNum: `${selectedRows.length}（件）` });
  };
  // 数量变化、失去焦点
  const countChange = (val, cur, record, myForm, type) => {
    val = parseFloat(val);
    // 输入为正整数，才计算金额
    console.log('aaa', val, Math.sign(val) === -1, Number.isInteger(val), Math.sign(val) === -1 || !Number.isInteger(val))
    if (Math.sign(val) === -1 || !Number.isInteger(val)) {
      if (type === 'change') {
        return;
      }
      val = parseFloat(parseFloat(val).toFixed(0));
    }
    if (Math.sign(val) === 1 && Number.isInteger(val)) {
      const tar = myForm.getFieldsValue()[record.rowKey];
      const dj = parseFloat(orderObj.discount_ratio) === 0 ? 0.01 : parseFloat(cur.goods_price) * parseFloat(orderObj.discount_ratio);
      console.log('blue', dj, val, record.rowIndex, record.rowKey, myForm.getFieldsValue());
      console.log('cur', cur);
      console.log('tar', tar);
      if (tar.goods_num <= cur.goods_num) {
        tar.refundPrice = parseFloat(dj * val).toFixed(2); // 最多可退
        orderObj.order_goods_list[record.rowIndex].maxRefund = tar.refundPrice;
      }
      myForm.setFieldsValue({ [record.rowKey]: tar });
      setOrderObj(orderObj);
      actionRef.current && actionRef.current?.reload();
      getTotalPrice();
    }
  }

  console.log('orderObj', orderObj)

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name',
      align: 'center',
      width: 150,
      editable: false,
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      align: 'center',
      editable: false,
      width: 150,
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      align: 'center',
      editable: false,
      width: 100,
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      width: '15%',
      align: 'center',
      editable: false,
      width: 150,
    },
    {
      title: '单品折扣',
      dataIndex: 'discount',
      align: 'right',
      editable: false,
    },
    {
      title: '折扣价',
      dataIndex: 'discount_price',
      align: 'right',
      editable: false,
    },
    {
      title: '订单折扣',
      dataIndex: 'discount_ratio',
      align: 'right',
      editable: false,
      // render: val => orderObj.discount_ratio
      render: (val, record, index) => {
        const obj = {
          children: orderObj.discount_ratio,
          props: {
            rowSpan: index === 0 ? orderObj.order_goods_list.length : 0
          },
        };
        return obj;
      }
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      align: 'right',
      editable: false
    },
    {
      title: '退款数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      align: 'right',
      width: 110,
      fieldProps: {
        precision: 0,
        // min: 1,
      },
      editable: (e, e1) => e1.goods_id !== '10086',
      formItemProps: (myForm, record) => {
        // console.log('数量', form.getFieldsValue());
        // console.log('record', record);
        const cur = orderObj.order_goods_list[record.rowIndex];
        return {
          rules: [{ required: true, message: '此项为必填项' },
          {
            validator: (e, val) => {
              if (val < 1) {
                return Promise.reject(new Error(`最多可退1!`));
              } else if (val > cur.goods_num) {
                return Promise.reject(new Error(`最多可退${cur.goods_num}!`));
              }
              return Promise.resolve();
            }, message: `最多可退${cur.goods_num}!`
          },
          ],
          onBlur: (e) => countChange(e.target.value, cur, record, myForm, 'blur'),
          onChange: (e) => countChange(e.target.value, cur, record, myForm, 'change'),
        };
      },
    },
    {
      title: '退款金额',
      dataIndex: 'refundPrice',
      valueType: 'money',
      align: 'right',
      width: 130,
      renderText: (val, record, index) => {
        return getMaxRefund(record, index);
      },
      formItemProps: (form, record) => {
        const cur = orderObj.order_goods_list[record.rowIndex];
        console.log('cur', cur, record);
        // let max = 0;
        // if (parseFloat(orderObj.discount_ratio) === 0) {
        //   max = parseFloat(cur.goods_num * 0.01).toFixed(2);
        // } else {
        //   max = parseFloat(parseFloat(cur.goods_total_price) * parseFloat(orderObj.discount_ratio)).toFixed(2);
        // }
        // if (record.rowIndex === orderObj.order_goods_list.length - 1) {
        //   max = parseFloat(parseFloat(max) + jy).toFixed(2);
        // }
        const max = getMaxRefund(cur, record.rowIndex);
        return {
          rules: [{ required: true, message: '此项为必填项' },
          {
            validator: (e, val) => {
              if (val > parseFloat(cur.maxRefund || parseFloat(max))) {
                return Promise.reject(new Error('111'));
              }
              return Promise.resolve();
            }, message: `最多可退${max}元`
          },
          {
            validator: (e, val) => {
              if (val <= 0) {
                return Promise.reject(new Error('111'));
              }
              return Promise.resolve();
            }, message: `退款金额不能为0`
          },
          ],
          onBlur: e => getTotalPrice(),
          onChange: e => getTotalPrice()
        };
      },
    },
  ];


  const columns_eye: ProColumns[] = [
    {
      title: '',
      dataIndex: 'c1',
      align: 'center',
      width: 110,
      render: (val) => <div style={{ fontWeight: 'bold' }}>{val}</div>
    },
    {
      title: '球镜',
      dataIndex: 'c2',
      align: 'center',
      width: 100
    },
    {
      title: '柱镜',
      dataIndex: 'c3',
      align: 'center',
      width: 100
    },
    {
      title: '轴位',
      dataIndex: 'c4',
      align: 'center',
      width: 100
    },
    {
      title: '矫正前视力',
      dataIndex: 'c5',
      align: 'center',
      width: 100
    },
    {
      title: '矫正后视力',
      dataIndex: 'c6',
      align: 'center',
      width: 100
    },
    {
      title: '瞳距',
      dataIndex: 'c7',
      align: 'center',
      width: 100
    },
    {
      title: '总瞳距',
      dataIndex: 'c8',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    },
    {
      title: '瞳高',
      dataIndex: 'c9',
      align: 'center',
      width: 100
    },
    {
      title: '离焦量',
      dataIndex: 'c11',
      align: 'center',
      width: 100
    },
    {
      title: 'ADD',
      dataIndex: 'c12',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    }
  ];

  const getGoodsNum = (list) => {
    let count = 0
    list.map(item => {
      count += item.goods_num;
    })
    return count;
  }

  // 判断是否需要显示配镜数据
  const getIsShow = () => {
    if (!isNull(orderObj.left_degrees) || !isNull(orderObj.left_astig) || !isNull(orderObj.left_axial) || !isNull(orderObj.right_degrees) || !isNull(orderObj.right_astig) || !isNull(orderObj.right_axial) || !isNull(orderObj.pup_distance) || !isNull(orderObj.after_left_version) || !isNull(orderObj.after_right_version) || !isNull(orderObj.before_left_version) || !isNull(orderObj.before_right_version)) {
      return true;
    }
    return false;
  }

  // 判断是否需要显示镜架数据
  const getFrameIsShow = () => {
    if (!isNull(orderObj.frame_back) || !isNull(orderObj.frame_diagonal) || !isNull(orderObj.frame_height) || !isNull(orderObj.frame_middle) || !isNull(orderObj.frame_width)) {
      return true;
    }
    return false;
  }

  console.log('结余', jy);

  let no = 3;
  return (
    <ModalForm
      form={form}
      title='退款'
      width={window.innerWidth > 1370 ? '80%' : "90%"}
      visible
      layout='horizontal'
      modalProps={{
        onCancel: () => onClose(),
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: '提交审批',
          resetText: '取消',
        },
      }}
      {...formItemLayout}
      initialValues={{
        ...orderObj,
        sett_price: `${orderObj.sett_price}（元）`,
        refundNum: `${selectedRow.length}（件）`,
      }}

      onFinish={async () => await onSubmit()}
    >
      <Spin spinning={loading}>
        <div className='common_title'>1.患者信息</div>
        <Divider />
        <Descriptions size="small" column={4}>
          <Descriptions.Item label="身份证/住院号">{orderObj.identity_no || '-'}/{orderObj.admission_num || '-'}</Descriptions.Item>
          <Descriptions.Item label="患者姓名">{orderObj.patient_name}</Descriptions.Item>
          <Descriptions.Item label="患者性别">{orderObj.patient_sex_name || '-'}</Descriptions.Item>
          <Descriptions.Item label="归属科室">{orderObj.create_dept_name}</Descriptions.Item>
        </Descriptions>
        <div className='common_title' style={{ margin: '10px 0' }}>2.选择退款商品</div>
        <Divider />
        <EditableProTable<DataSourceType>
          rowKey="id"
          size='small'
          // style={{ marginTop: -8 }}
          bordered
          columns={columns}
          actionRef={actionRef}
          loading={loading}
          className='dialogTable'
          request={async () => ({
            data: () => orderObj.order_goods_list.map((item) => { return { ...item, id: item.record_id } }),
            success: true
          })}
          search={false}
          options={false}
          pagination={false}
          recordCreatorProps={false}
          value={dataSource}
          onChange={setDataSource}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: false,
            onChange: selectRow
          }}
          tableAlertRender={false}
          editable={{
            form: editForm,
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
        {
          getIsShow() &&
          <>
            <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.配镜信息`}</div>
            <Divider />
            <ProTable
              rowKey="id"
              size='small'
              bordered
              // style={{ margin: '0 -24px' }}
              columns={columns_eye}
              // actionRef={actionRef1}
              search={false}
              options={false}
              dataSource={ygData}
              pagination={false}
            />
            <Descriptions column={4}>
              <Descriptions.Item span={1} label="用途">{museText[orderObj?.muse] || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="验光号" className='print_no'>{orderObj.sight_no || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="就诊医生" className='print_no'>{orderObj.doctor_name || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="验光师" className='print_no'>{orderObj.optician_name || '-'}</Descriptions.Item>
              <Descriptions.Item span={3} label="特殊备注">{orderObj.special_case || '-'}</Descriptions.Item>
            </Descriptions>
          </>
        }
        {
          getFrameIsShow() &&
          <>
            <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.镜架信息`}</div>
            <Divider />
            <Descriptions column={4}>
              <Descriptions.Item span={1} label="框宽">{orderObj.frame_width || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="框高">{orderObj.frame_height || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="中梁">{orderObj.frame_middle || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="镜对角直径">{orderObj.frame_diagonal || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="型号">{orderObj.frame_model || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="框型">{orderObj.frame_material || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="是否需要防滑套">{orderObj.is_slip === 'Y' ? '需要' : '不需要'}</Descriptions.Item>
              <Descriptions.Item span={1} label="是否自备镜架">
                {(orderObj.frame_flag ?? '0') == '0' ? '非自备' : (orderObj.frame_flag == '1' ? '自备/留' : '自备/未留')}
              </Descriptions.Item>
            </Descriptions>
          </>
        }
        <div className='common_title' style={{ marginBottom: 10, marginTop: 10 }}>{`${no++}.退款结算信息`}</div>
        <Divider />
        <Descriptions size="small" column={3}>
          <Descriptions.Item label="订单支付金额"><span className='bold'>{orderObj.sett_price}</span>（元）</Descriptions.Item>
          <Descriptions.Item label="退款商品数量"><span className='red bold'>{getGoodsNum(selectedRow)}</span>（件）</Descriptions.Item>
          <Descriptions.Item label="退款金额"><span className='red bold'>{total}</span>（元）</Descriptions.Item>
        </Descriptions>
      </Spin>
      {contextHolder}
    </ModalForm>
  );
};

export default Refund;
